/*!
 * Page: mine/add-user-verification/AddUserVerification
 * License: MIT
 * Created: 2019-09-18 15:18
 */

import { uploadFile } from '/api/file'
import { userApi } from '/api/user'
import { getDomoUser } from '/store/actions'
import { getServer } from '/store/mutations'
import { GlobalData } from '/store/state'
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
//@ts-ignore
import getMessage from 'ts-msg-handler'

Page({
  data: {
    isFullScreen: GlobalData.isFullScreen,
    form: {
      type: 'user',
      data: {
        id_card: {
          front: '' as string, // 身份证正面照片
          rear: '' as string, // 身份证背面照片
          number: '' as string, // 身份证号吗
        } as any,
        real_name: '' as string, // 真实信息
        phone_number: '' as string, // 手机号码
        desc: '' as string,
      },
    } as UpdateVerificationUserPayload,
    update: false,
    verification: {} as any,
    submitting: false as boolean,
    canSubmit: false as boolean,
    front: '' as string,
    rear: '' as string,
    frontTmp: '' as string,
    rearTmp: '' as string,
    frontShow: false,
    rearShow: false,
    imageParams: {
      width: 243,
      height: 153,
      max_width: 486,
      max_height: 306,
      export_scale: 1,
      disable_rotate: true,
      disable_ratio: true,
      limit_move: true,
      src: '' as string,
      show: false,
      scale: 1,
    },
    rearCropper: '' as any,
    frontCropper: '' as any,
    /** 是否是重新认证 */
    reVeiryfied: false,
  },
  /** 如果需要更改，则加载当前登录用户 */
  onLoad(query) {
    this.setData({
      isFullScreen: GlobalData.isFullScreen,
      reVeiryfied: query.isReVeiryfied as unknown as boolean,
    })
    if (query.load) {
      this.getUserInfo()
    }
  },
  /** 取消选择图片 */
  cancel() {
    this.setData({
      rearShow: false,
      frontShow: false,
    })
  },
  getUserInfo() {
    const server = getServer()
    const user = wx.getStorageSync(`${server}/logged`).data || {}
    this.setData({
      form: {
        type: 'user',
        data: {
          id_card: {
            front: user.verification.id_card.front.node,
            number: user.verification.id_card.number,
            rear: user.verification.id_card.rear.node,
          },
          real_name: user.verification.real_name,
          phone_number: user.verification.phone_number,
          desc: user.verification.desc,
        },
      },
      front: user.verification.id_card.front.node,
      rear: user.verification.id_card.rear.node,
      update: true,
      canSubmit: true,
      verification: user.verification,
    })
  },
  onShow() {
    this.setData({
      // @ts-ignore
      rearCropper: this.selectComponent('#image-cropper-rear'),
      // @ts-ignore
      frontCropper: this.selectComponent('#image-cropper-front'),
    })
  },
  handleConfirm({
    detail: { value },
    target: {
      dataset: { type },
    },
  }: {
    detail: any
    target: any
    type: string
  }) {
    switch (type) {
      case 'real_name':
        this.setData(
          {
            form: {
              ...this.data.form,
              data: {
                ...this.data.form.data,
                real_name: value,
              },
            },
          },
          () => {
            this.computeCanSubmit()
          },
        )
        break
      case 'phone_number':
        this.setData(
          {
            form: {
              ...this.data.form,
              data: {
                ...this.data.form.data,
                phone_number: value,
              },
            },
          },
          () => {
            this.computeCanSubmit()
          },
        )
        break
      case 'desc':
        this.setData(
          {
            form: {
              ...this.data.form,
              data: {
                ...this.data.form.data,
                desc: value,
              },
            },
          },
          () => {
            this.computeCanSubmit()
          },
        )
        break
      case 'identify':
        this.setData(
          {
            form: {
              ...this.data.form,
              data: {
                ...this.data.form.data,
                id_card: {
                  ...this.data.form.data.id_card,
                  number: value,
                },
              },
            },
          },
          () => {
            this.computeCanSubmit()
          },
        )
        break
    }
  },
  clickcut(e: any) {
    //图片预览
    wx.previewImage({
      current: e.detail.url, // 当前显示图片的http链接
      urls: [e.detail.url], // 需要预览的图片http链接列表
    })
  },
  submitFront() {
    this.data.frontCropper.getImg((obj: any) => {
      this.setData(
        {
          frontShow: false,
          frontTmp: obj.url,
        },
        () => {
          this.computeCanSubmit()
        },
      )
    })
  },
  computeCanSubmit() {
    const { frontTmp, rearTmp } = this.data
    const {
      phone_number,
      desc,
      real_name,
      id_card: { number },
    } = this.data.form.data
    this.setData({
      canSubmit: !!(
        phone_number &&
        desc &&
        real_name &&
        (this.data.front || frontTmp) &&
        (this.data.rear || rearTmp) &&
        number
      ),
    })
  },
  submitRear() {
    this.data.rearCropper.getImg((obj: any) => {
      this.setData(
        {
          rearShow: false,
          rearTmp: obj.url,
        },
        () => {
          this.computeCanSubmit()
        },
      )
    })
  },
  handleBgTap(e: any) {
    const {
      target: {
        dataset: { type },
      },
    } = e
    wx.chooseImage({
      success: ({ tempFilePaths: { [0]: path } }) => {
        this.setData({
          imageParams: {
            ...this.data.imageParams,
            src: path,
          },
          [`${type}Show`]: true,
        })
      },
    })
  },
  async doSubmit() {
    const { frontTmp, rearTmp, update, form } = this.data
    let {
      data: { front, rear },
    } = this
    this.setData({
      submitting: true,
    })
    // 第一次创建的时候
    if (!update) {
      if (!front) {
        if (!frontTmp) {
          wx.showToast({
            title: '请选择身份证正面图片',
            icon: 'none',
          })
          this.setData({
            submitting: false,
          })
          return
        }
        try {
          front = await uploadFile(frontTmp)
          this.setData({ front })
        } catch (error) {
          wx.showToast({ title: `${getMessage(error.data).getMessage()}`, icon: 'none' })
          return
        }
      }
      form.data.id_card.front = front
      if (!rear) {
        if (!rearTmp) {
          wx.showToast({
            title: '请选择身份证背面图片',
            icon: 'none',
          })
          this.setData({
            submitting: false,
          })
          return
        }
        try {
          rear = await uploadFile(rearTmp)
          this.setData({ rear })
        } catch (error) {
          wx.showToast({ title: `${getMessage(error.data).getMessage()}`, icon: 'none' })
          return
        }
      }
      form.data.id_card.rear = rear
    } else {
      try {
        // 重新认证
        if (frontTmp) {
          // 如果检测到有身份证正面临时文件，则上传
          front = await uploadFile(frontTmp)
          form.data.id_card.front = front
          this.setData({ front })
        }
        // 重新认证
        if (rearTmp) {
          // 如果检测到有身份证背面临时文件，则上传
          rear = await uploadFile(rearTmp)
          form.data.id_card.front = rear
          this.setData({ rear })
        }
      } catch (error) {
        wx.showToast({ title: `${getMessage(error.data).getMessage()}`, icon: 'none' })
        return
      }
    }
    const method = update ? 'updateVerification' : 'saveVerification'

    // 重新认证，需要吸纳删除以前的认证
    if (this.data.reVeiryfied) {
      await userApi.deleteVerification()
    }
    userApi[method](form)
      .then(() => {
        this.setData(
          {
            submitting: false,
          },
          () => {
            wx.showToast({
              title: '成功，待审核',
              duration: 1500,
            })
            getDomoUser()
            setTimeout(() => {
              wx.switchTab({
                url: '/pages/user/user',
              })
            }, 1500)
          },
        )
      })
      .catch((data: { data: {} }) => {
        this.setData(
          {
            submitting: false,
          },
          () => {
            wx.showToast({ title: `${getMessage(data.data).getMessage()}`, icon: 'none' })
            setTimeout(() => {
              wx.navigateTo({
                url: '/pages/user/user',
              })
            }, 1500)
          },
        )
      })
  },
})
